package com.costeaalex.MIDlets.remote.bluetooth;

import javax.bluetooth.BluetoothStateException;
import javax.bluetooth.DeviceClass;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;
import javax.bluetooth.UUID;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;

import com.costeaalex.MIDlets.remote.BlueMIDlet;

public class ServiceFinder implements DiscoveryListener
	{
	
	private RemoteDevice rD;
	private BlueMIDlet midlet;
	private int[] attrList = {0x0003, 0x0000, 0x0004, 0x100, 0x101, 0x102};
	private UUID[][] uuids = null;
	private DiscoveryAgent discoveryAgent=null;
	
	public ServiceRecord[] btServicesFound;
	
	public ServiceFinder(BlueMIDlet midl)
		{
		midlet=midl;
		}

	public void findServices(RemoteDevice remoteDev)
		{
		LocalDevice local;
		rD=remoteDev;
		try
			{
			local = LocalDevice.getLocalDevice();
			discoveryAgent = local.getDiscoveryAgent();
			uuids = new UUID[9][1];
			
			uuids[0][0] = new UUID(0x0001);
			uuids[1][0] = new UUID(0x0003);
			uuids[2][0] = new UUID(0x0008);
			uuids[3][0] = new UUID(0x000c);
			uuids[4][0] = new UUID(0x0100);
			uuids[5][0] = new UUID(0x1101);//only SPP is used
			uuids[6][0] = new UUID(0x1105);
			uuids[7][0] = new UUID(0x1106);
			uuids[8][0] = new UUID(0x1115);
			
			discoveryAgent.searchServices(attrList, uuids[5], rD, this);
			}
		catch (BluetoothStateException e)
			{
			Alert error = new Alert("Error", "Unable to start service search ("+e.getMessage()+")",null, AlertType.ERROR);
			error.setTimeout(Alert.FOREVER);
			e.printStackTrace();
			}
		}

	public void deviceDiscovered(RemoteDevice arg0, DeviceClass arg1)
		{
		}

	public void inquiryCompleted(int param)
		{
		}

	public void serviceSearchCompleted(int transID, int type)
		{
		midlet.servicesFound(btServicesFound);
		}

	public void servicesDiscovered(int transIS, ServiceRecord[] record)
		{
		btServicesFound=record;
		}
	}
